#ifndef __MUTEX_LOCK_H__
#define __MUTEX_LOCK_H__

#include <pthread.h>

class MutexLock
{
 public:
  MutexLock()  // 为了节省版面，单行函数都没有正确缩进
  { pthread_mutex_init(&mutex_, NULL); }

  ~MutexLock()
  { pthread_mutex_destroy(&mutex_); }

  void lock()  // 程序一般不主动调用
  { pthread_mutex_lock(&mutex_); }

  void unlock()  // 程序一般不主动调用
  { pthread_mutex_unlock(&mutex_); }

  pthread_mutex_t* getPthreadMutex()  // 仅供 Condition 调用，严禁自己调用
  { return &mutex_; }

 private:
  // 禁用拷贝
  MutexLock(const MutexLock&);
  MutexLock& operator=(const MutexLock&);

 private:
  pthread_mutex_t mutex_;
};

class MutexLockGuard
{
 public:
  explicit MutexLockGuard(MutexLock& mutex) : mutex_(mutex)
  { mutex_.lock(); }

  ~MutexLockGuard()
  { mutex_.unlock(); }

 private:
  // 禁用拷贝
  MutexLockGuard(const MutexLockGuard&);
  MutexLockGuard& operator=(const MutexLockGuard&);

 private:
  MutexLock& mutex_;
};

#define MutexLockGuard(x) static_assert(false, "missing mutex guard var name")

#endif